#include <stdlib.h>
#include <stdio.h>
#include <signal.h>

#include "base.hpp"

#include "acceptor_manager.hpp"
#include "abstract_processor.hpp"
#include "abstract_parser.hpp"
#include "connection.hpp"

using namespace mina;

#define MAX_UINT32 0xffffffffLLU

#ifdef _DEBUG 
 
// #define MAX_LOOP        400000LLU 
#define MAX_LOOP        40
 
#define MAX_THREAD_NUM  4
#define MAX_CONNECTOR_NUM_FOR_TEST 1
 
#endif 

#define MAX_PACK_SIZE   59
#define PACK_BASE_SIZE  50

#define STR_MAX_SIZE   100

struct Parser : public AbstractParser
{
	int encode(ListBuffer & listbuffer, void * data)
	{
		char * str = (char*)data;
		int len = strlen(str);

		listbuffer.copy_in_s(str, len);
		listbuffer.produce(len);
		
		return 0;
	}

	int  decode(ListBuffer & listbuffer, void *& data)
	{
		return 0;
	}

	bool frame(ListBuffer & listbuffer)
	{
		return true;
	}
};

struct Processor : public AbstractProcessor
{
	void accept_connect(Connection & conn) {}
	void remove_connect(Connection & conn) {}

	void process_message(Connection & conn, void * data) {}
};

int main(int argc, char * argv[])
{
	log4cplus::PropertyConfigurator::doConfigure("logger.properties");

	NetAddr addr("127.0.0.1", 80);

	MemoryPool * pool = new MemoryPool(1024, 1024 * 4);
	
	BufferAlloc * alloc = new PoolBufferAlloc(*pool);

	Parser parser;
	Processor processor;

	Connection * conn = new Connection(*alloc, addr, parser, processor);

	assert(0 == conn->connect(false));

	std::string request="GET /cgi-bin/helloworld?openid=0x23 HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";

	std::cout << "request: " << request << std::endl;

	int size = request.size();
	assert(size == conn->sync_write((void*)request.c_str()));

	while (true)
	{
		int ret = conn->sync_read(1024 * 1024, 100000000);

		if (ret < 0)
		{
			std::cout << ret << "(" << net_err_2_str(ret) << ")" << std::endl;
			break;
		}

		std::string http;

		conn->_rd_buff.copy_out(http, -1);

		std::cout << http;

		break;
	}

	return 0;
}

